﻿using Microsoft.SharePoint.Utilities;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Mazin.SPGoogleMapPart
{
    [ToolboxItem(false)]
    public class MapEditorPart : EditorPart
    {
        private const string ItemHeader = "</div><div class=\"UserDottedLine\" style=\"width: 100%;\"/></td></tr><tr {1}><td><div class=\"UserSectionHead\"><label>{0}</label></div><div class=\"UserSectionBody\">";

        private CheckBox _httpsCheckbox;
        private CheckBox _clustererCheckbox;
        private CheckBox _panCheckbox;
        private CheckBox _zoomCheckbox;
        private CheckBox _mapTypeCheckbox;
        private CheckBox _streetviewCheckbox;
        private CheckBox _ribbonCheckbox;
        private TextBox _addressColumnName;
        private TextBox _camlQuery;
        private TextBox _centreLatitude;
        private TextBox _centreLongitude;
        private DropDownList _dataMode;
        private TextBox _descrColumName;
        private DropDownList _initialZoom;
        private TextBox _latColumnName;
        private TextBox _listUrl;
        private TextBox _lngColumnName;
        private TextBox _mapHeight;
        private DropDownList _mapType;
        private TextBox _mapWidth;
        private TextBox _titleColumnName;
        private TextBox _urlIdParamName;
        private TextBox _webUrl;
        private TextBox _iconUrl;

        private TextBox _proxyUlr;
        private TextBox _proxyUserName;
        private TextBox _proxyPassword;

        private TextBox _apiKey;

        private bool _isSandbox;

        protected override void CreateChildControls()
        {
            uint lang = (uint)System.Threading.Thread.CurrentThread.CurrentUICulture.LCID;

            _isSandbox = AppDomain.CurrentDomain.FriendlyName.Contains("Sandbox");

            LiteralControl control = new LiteralControl("<table style=\"width: 100%; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-collapse: collapse;\" border=\"0\" cellSpacing=\"0\"><tr><td><div class=\"UserSectionHead\"><label>HTTPS</label></div><div class=\"UserSectionBody\">");
            Controls.Add(control);
            _httpsCheckbox = new CheckBox();
            _httpsCheckbox.ToolTip = SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,HttpsControlTitle", null, lang);
            Controls.Add(_httpsCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,DisplayRibbonLabel", null, lang), string.Empty));
            Controls.Add(control);
            _ribbonCheckbox = new CheckBox();
            _ribbonCheckbox.ToolTip = SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,DisplayRibbonTitle", null, lang);
            Controls.Add(_ribbonCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorApiKeyLabel", null, lang), string.Empty));
            Controls.Add(control);
            _apiKey = new TextBox { CssClass = "UserInput" };
            Controls.Add(_apiKey);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,MarkerClustererControlLabel", null, lang), string.Empty));
            Controls.Add(control);
            _clustererCheckbox = new CheckBox();
            Controls.Add(_clustererCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorPanControlLabel", null, lang), string.Empty));
            Controls.Add(control);
            _panCheckbox = new CheckBox();
            Controls.Add(_panCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorZoomControlLabel", null, lang), string.Empty));
            Controls.Add(control);
            _zoomCheckbox = new CheckBox();
            Controls.Add(_zoomCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapTypeControlLabel", null, lang), string.Empty));
            Controls.Add(control);
            _mapTypeCheckbox = new CheckBox();
            Controls.Add(_mapTypeCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorStreetViewControlLabel", null, lang), string.Empty));
            Controls.Add(control);
            _streetviewCheckbox = new CheckBox();
            Controls.Add(_streetviewCheckbox);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapTypeLabel", null, lang), string.Empty));
            Controls.Add(control);
            _mapType = new DropDownList();
            _mapType.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapTypeHybrid", null, lang), "HYBRID"));
            _mapType.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapTypeRoadMap", null, lang), "ROADMAP"));
            _mapType.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapTypeSatellite", null, lang), "SATELLITE"));
            _mapType.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapTypeTerrain", null, lang), "TERRAIN"));
            Controls.Add(_mapType);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorCentrLatLabel", null, lang), string.Empty));
            Controls.Add(control);
            _centreLatitude = new TextBox();
            _centreLatitude.CssClass = "UserInput";
            _centreLatitude.Attributes.Add("onchange", "ValidateDouble(this);");
            Controls.Add(_centreLatitude);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorCentrLngLabel", null, lang), string.Empty));
            Controls.Add(control);
            _centreLongitude = new TextBox {CssClass = "UserInput"};
            _centreLongitude.Attributes.Add("onchange", "ValidateDouble(this);");
            Controls.Add(_centreLongitude);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapHeightLabel", null, lang), string.Empty));
            Controls.Add(control);
            _mapHeight = new TextBox();
            _mapHeight.CssClass = "UserInput";
            _mapHeight.Attributes.Add("onchange", "ValidateInt(this);");
            Controls.Add(_mapHeight);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorMapWidthLabel", null, lang), string.Empty));
            Controls.Add(control);
            _mapWidth = new TextBox();
            _mapWidth.CssClass = "UserInput";
            _mapWidth.Attributes.Add("onchange", "ValidateInt(this);");
            Controls.Add(_mapWidth);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomLabel", null, lang), string.Empty));
            Controls.Add(control);
            _initialZoom = new DropDownList();
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem17Label", null, lang), "17"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem16Label", null, lang), "16"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem15Label", null, lang), "15"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem14Label", null, lang), "14"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem13Label", null, lang), "13"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem12Label", null, lang), "12"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem11Label", null, lang), "11"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem10Label", null, lang), "10"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem9Label", null, lang), "9"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem8Label", null, lang), "8"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem7Label", null, lang), "7"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem6Label", null, lang), "6"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem5Label", null, lang), "5"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem4Label", null, lang), "4"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem3Label", null, lang), "3"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem2Label", null, lang), "2"));
            _initialZoom.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorInitZoomItem1Label", null, lang), "1"));
            Controls.Add(_initialZoom);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorIconUrlLabel", null, lang), string.Empty));
            Controls.Add(control);
            _iconUrl = new TextBox();
            _iconUrl.CssClass = "UserInput";
            _iconUrl.ToolTip = SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorIconUrlToolTip", null, lang);
            Controls.Add(_iconUrl);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeLabel", null, lang), string.Empty));
            Controls.Add(control);
            _dataMode = new DropDownList();
            _dataMode.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeItem0Label", null, lang), "0"));
            _dataMode.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeItem1Label", null, lang), "1"));
            _dataMode.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeItem2Label", null, lang), "2"));
            _dataMode.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeItem3Label", null, lang), "3"));
            _dataMode.Attributes.Add("onchange", "DataModeChanged(this)");
            _dataMode.ToolTip = SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeToolTip", null, lang);
            Controls.Add(_dataMode);

            control = new LiteralControl(SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDataModeDescription", null, lang));
            Controls.Add(control);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorWebUrlLabel", null, lang), "id=\"list\""));
            Controls.Add(control);
            _webUrl = new TextBox {CssClass = "UserInput"};
            Controls.Add(_webUrl);

            control =
                new LiteralControl(
                    string.Format(
                        "</div><br/><div class=\"UserSectionHead\"><label>{0}</label></div><div class=\"UserSectionBody\">",
                        SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorListUrlLabel", null, lang)));
            Controls.Add(control);
            _listUrl = new TextBox();
            _listUrl.CssClass = "UserInput";
            Controls.Add(_listUrl);
            control =
                new LiteralControl(
                    string.Format("&nbsp;<input type=\"button\" value=\"{0}\" onclick=\"portal_openModalDialog()\" />", SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorListUrlBrowseLabel", null, lang)));
            Controls.Add(control);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorCamlQueryLabel", null, lang), "id=\"query\""));
            Controls.Add(control);
            _camlQuery = new TextBox();
            _camlQuery.CssClass = "UserInput";
            Controls.Add(_camlQuery);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorIdParametrLabel", null, lang), "id=\"itemId\""));
            Controls.Add(control);
            _urlIdParamName = new TextBox();
            _urlIdParamName.CssClass = "UserInput";
            _urlIdParamName.ToolTip = SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorIdParameterToolTip", null, lang);
            Controls.Add(_urlIdParamName);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorTitleColumnLabel", null, lang), string.Empty));
            Controls.Add(control);
            _titleColumnName = new TextBox();
            _titleColumnName.CssClass = "UserInput";
            Controls.Add(_titleColumnName);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorDescrColumnLabel", null, lang), string.Empty));
            Controls.Add(control);
            _descrColumName = new TextBox();
            _descrColumName.CssClass = "UserInput";
            Controls.Add(_descrColumName);

            if (!_isSandbox)
            {
                control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorAddressColumnLabel", null, lang), string.Empty));
                Controls.Add(control);
                _addressColumnName = new TextBox();
                _addressColumnName.CssClass = "UserInput";
                Controls.Add(_addressColumnName);

                control = new LiteralControl("<br/><br/>" + SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorProxyDescription", null, lang));
                Controls.Add(control);

                control = new LiteralControl(string.Format("</div><br/><div class=\"UserSectionHead\"><label>{0}</label></div><div class=\"UserSectionBody\">", SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorProxyUrlLabel", null, lang), string.Empty));
                Controls.Add(control);
                _proxyUlr = new TextBox();
                _proxyUlr.CssClass = "UserInput";
                Controls.Add(_proxyUlr);

                control = new LiteralControl(string.Format("</div><br/><div class=\"UserSectionHead\"><label>{0}</label></div><div class=\"UserSectionBody\">", SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorProxyUserNameLabel", null, lang), string.Empty));
                Controls.Add(control);
                _proxyUserName = new TextBox();
                _proxyUserName.CssClass = "UserInput";
                Controls.Add(_proxyUserName);

                control = new LiteralControl(string.Format("</div><br/><div class=\"UserSectionHead\"><label>{0}</label></div><div class=\"UserSectionBody\">", SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorProxyPasswordLabel", null, lang), string.Empty));
                Controls.Add(control);
                _proxyPassword = new TextBox();
                _proxyPassword.CssClass = "UserInput";
                Controls.Add(_proxyPassword);
            }

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorLatColumnLabel", null, lang), string.Empty));
            Controls.Add(control);
            _latColumnName = new TextBox();
            _latColumnName.CssClass = "UserInput";
            Controls.Add(_latColumnName);

            control = new LiteralControl(string.Format(ItemHeader, SPUtility.GetLocalizedString("$Resources:SPGoogleMapPart,EditorLngColumnLabel", null, lang), string.Empty));
            Controls.Add(control);
            _lngColumnName = new TextBox();
            _lngColumnName.CssClass = "UserInput";
            Controls.Add(_lngColumnName);

            control =
                new LiteralControl(
                    String.Format(
                        "<script type=\"text/javascript\" src=\"/_layouts/1033/pickertreedialog.js\"></script><script type=\"text/javascript\">function ValidateInt(control) {{var tmp = parseInt(control.value);return !isNaN(tmp);}}function ValidateDouble(control) {{var tmp = parseFloat(control.value);return !isNaN(tmp);}}function DataModeChanged(control) {{if (control.value == \"0\" || control.value == \"3\") {{document.getElementById(\"list\").style.display = 'none';document.getElementById(\"itemId\").style.display = 'none';document.getElementById(\"query\").style.display = 'none';return;}}if (control.value == \"1\") {{document.getElementById(\"list\").style.display = '';document.getElementById(\"query\").style.display = '';document.getElementById(\"itemId\").style.display = 'none';return;}}if (control.value == \"2\") {{document.getElementById(\"list\").style.display = '';document.getElementById(\"itemId\").style.display = '';document.getElementById(\"query\").style.display = 'none';return;}}}}" +
                        "function portal_openModalDialog() {{ var callback = function (dest) {{ if (dest != null && dest != undefined && dest[3] != null) {{ document.getElementById('{0}').value = dest[1];document.getElementById('{1}').value = dest[3]; }} }};" +
                        "SP.SOD.executeFunc('pickertreedialog.js', 'LaunchPickerTreeDialogSelectUrl', function () {{ LaunchPickerTreeDialogSelectUrl('CbqPickerSelectListTitle', 'CbqPickerSelectListText', 'websListsFolders', '', '', '', '', '', \"/_layouts/15/images/smt_icon.gif?rev=32\", '', callback, 'true', '');}});" +
                        "}} DataModeChanged(document.getElementById('{2}'))</script>", _webUrl.ClientID, _listUrl.ClientID, _dataMode.ClientID));
            Controls.Add(control);
        }

        public override bool ApplyChanges()
        {
            //from editorpart tu webpart properties
            try
            {
                var webpart = (VisualWebPart) WebPartToEdit;
                webpart.ZoomLevel = int.Parse(_initialZoom.Text);
                webpart.MapWidth = int.Parse(_mapWidth.Text);
                webpart.MapHeight = int.Parse(_mapHeight.Text);
                webpart.WebUrl = _webUrl.Text;
                webpart.TitleColumn = _titleColumnName.Text;
                webpart.MapType = _mapType.Text;
                webpart.LongitudeColumn = _lngColumnName.Text;
                webpart.LatitudeColumn = _latColumnName.Text;
                webpart.ListUrl = _listUrl.Text;
                webpart.ListQuery = _camlQuery.Text;
                webpart.ListItemIdParamName = _urlIdParamName.Text;
                webpart.CentreLongitude = double.Parse(_centreLongitude.Text);
                webpart.CentreLatitude = double.Parse(_centreLatitude.Text);
                webpart.DescriptionColumn = _descrColumName.Text;
                webpart.DataMode = int.Parse(_dataMode.SelectedValue);
                webpart.Https = _httpsCheckbox.Checked;
                webpart.PanControl = _panCheckbox.Checked;
                webpart.ZoomControl = _zoomCheckbox.Checked;
                webpart.MapTypeControl = _mapTypeCheckbox.Checked;
                webpart.StreetViewControl = _streetviewCheckbox.Checked;
                webpart.UseClusterer = _clustererCheckbox.Checked;
                webpart.IconUrl = _iconUrl.Text;
                webpart.ProxyUserName = _proxyUserName.Text;
                webpart.ProxyPassword = _proxyPassword.Text;
                webpart.ProxyUrl = _proxyUlr.Text;
                webpart.ApiKey = _apiKey.Text;
                webpart.DisplayRibbon = _ribbonCheckbox.Checked;

                if (!_isSandbox)
                {
                    webpart.AddressColumn = _addressColumnName.Text;
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public override void SyncChanges()
        {
            //from webpart to editpart
            var webpart = (VisualWebPart) WebPartToEdit;
            EnsureChildControls();
            _initialZoom.Text = webpart.ZoomLevel.ToString(CultureInfo.InvariantCulture);
            _mapWidth.Text = webpart.MapWidth.ToString(CultureInfo.InvariantCulture);
            _mapHeight.Text = webpart.MapHeight.ToString(CultureInfo.InvariantCulture);
            _webUrl.Text = webpart.WebUrl;
            _titleColumnName.Text = webpart.TitleColumn;
            _mapType.SelectedValue = webpart.MapType;
            _lngColumnName.Text = webpart.LongitudeColumn;
            _latColumnName.Text = webpart.LatitudeColumn;
            _listUrl.Text = webpart.ListUrl;
            _camlQuery.Text = webpart.ListQuery;
            _urlIdParamName.Text = webpart.ListItemIdParamName;
            _centreLongitude.Text = webpart.CentreLongitude.ToString(CultureInfo.InvariantCulture);
            _centreLatitude.Text = webpart.CentreLatitude.ToString(CultureInfo.InvariantCulture);
            _descrColumName.Text = webpart.DescriptionColumn;
            _dataMode.SelectedValue = webpart.DataMode.ToString(CultureInfo.InvariantCulture);
            _httpsCheckbox.Checked = webpart.Https;

            _panCheckbox.Checked = webpart.PanControl;
            _zoomCheckbox.Checked = webpart.ZoomControl;
            _mapTypeCheckbox.Checked = webpart.MapTypeControl;
            _streetviewCheckbox.Checked = webpart.StreetViewControl;
            _clustererCheckbox.Checked = webpart.UseClusterer;

            _iconUrl.Text = webpart.IconUrl;
            if (!_isSandbox)
            {
                _addressColumnName.Text = webpart.AddressColumn;
                _ribbonCheckbox.Checked = webpart.DisplayRibbon;
                _proxyPassword.Text = webpart.ProxyPassword;
                _proxyUserName.Text = webpart.ProxyUserName;
                _proxyUlr.Text = webpart.ProxyUrl;
            }

            _apiKey.Text = webpart.ApiKey;
        }
    }
}
